package com.zlsy.secondtime.background;

/**
 * @author zhouliang
 * @date 2020/5/26 10:32
 * 用工厂模式修复注册监听隐式溢出
 */
public class MultiThreadsError7 {

    private int count;
    private EventLisenler eventLisenler;

    private MultiThreadsError7(MySource mySource) {
        eventLisenler = new EventLisenler() {
            @Override
            public void onEvent(Event event) {
                System.out.println("我得到的数字为：" + count);
            }
        };

        for (int i = 0; i < 1000; i++) {
            System.out.print(i);
        }
        count = 100;
    }

    public static MultiThreadsError7 getInstance(MySource source) {

        MultiThreadsError7 safeLisenler = new MultiThreadsError7(source);

        source.registerEventListener(safeLisenler.eventLisenler);

        return safeLisenler;

    }

    public static void main(String[] args) throws InterruptedException {

        MySource mySource = new MySource();

        MultiThreadsError7 instance = MultiThreadsError7.getInstance(mySource);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                mySource.enevtCome(new Event() {
                });
            }
        });
        Thread.sleep(10);
        thread.start();

    }


    static class MySource {

        private EventLisenler eventLisenler;

        void registerEventListener(EventLisenler eventLisenler) {
            this.eventLisenler = eventLisenler;
        }

        void enevtCome(Event e) {
            if (eventLisenler != null) {
                eventLisenler.onEvent(e);
            } else {
                System.out.println("还未初始化完毕！");
            }
        }

    }

    interface Event {
    }

    interface EventLisenler {
        void onEvent(Event event);
    }
}
